package com.qikux.entity;

import com.qikux.consts.AppConst;
import com.qikux.listener.UserManager;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder(toBuilder = true)
public class User extends Entity implements HttpSessionBindingListener {

    private String tel;

    private String password;

    private String email;

    private int enable;

    private UserInfo info;

    /**
     * 监听 是否向 session 中，添加了 User
     * @param event
     */
    @Override
    public void valueBound(HttpSessionBindingEvent event) {

        ServletContext servletContext = event.getSession().getServletContext();

        UserManager userManager = (UserManager)servletContext.getAttribute(AppConst.USER_MANAGER);

        // 获取 向 session中，添加的 键
        String key = event.getName();
        User user = (User) event.getValue() ;

        // 判断 key 是不是 登录标记 ，如果是 则将 登录的用户存放到 用户管理中

        if (AppConst.LOGIN_FLAG.equals(key)) {
            userManager.addUser(user, event.getSession());
        }
    }

    /**
     * 当 移除 session标识的时候， 或者 session失效的时候触发的代码
     * @param event
     */
    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {

        ServletContext servletContext = event.getSession().getServletContext();
        UserManager userManager = (UserManager)servletContext.getAttribute(AppConst.USER_MANAGER);
        // 获取 移除的用户对象
        String key = event.getName();
        User user = (User) event.getValue() ;

        if (AppConst.LOGIN_FLAG.equals(key)) {
            userManager.removeUser(user);
        }
    }
}
